﻿using System;
using System.Collections.Generic;
using Engine;
using Game;

namespace Mekiasm
{
    //合成谱
    public class MekCraftingRecipe
    {
        public static Dictionary<Interface.IDynamicCraft, List<MekRecipe>> MekRecipes = new Dictionary<Interface.IDynamicCraft, List<MekRecipe>>();

        public static Interface.IDynamicCraft FindCraftDevice(Type type)
        {
            foreach (var c in MekRecipes.Keys)
            {
                if (c.GetType() == type) return c;
            }
            return null;
        }

        public static MekRecipe MatchMekRecipe(Interface.IDynamicCraft dynamicCraft, string[] ingredians, string[] fuelingredians,ComponentEnergyMachine.FuelType[] fuelIngredianTypes, long[] fuelIngredianAmount, ComponentEnergyMachine machine, float heatLevel, ComponentPlayer player)
        {
            if (MekRecipes.TryGetValue(dynamicCraft, out var list))
            {
                foreach (var item in list)
                {
                    if (item.Match(ingredians, fuelingredians, fuelIngredianTypes, fuelIngredianAmount, machine, heatLevel, player)) return item;
                }
            }
            return null;
        }

        /// <summary>
        /// 变换摆谱从0,0开始
        /// </summary>
        /// <param name="inventory">箱子</param>
        /// <param name="size">合成配方大小，如3x3</param>
        /// <param name="result">重新摆谱后的结果</param>
        public static void TransformInventory(IInventory inventory, Point2 size, ref int[] result, int startIndex = 0)
        {
            int max = size.X * size.Y;
            result = new int[max];
            Point2 point = size;
            for (int i = 0; i < size.Y; i++)
            {//y
                for (int j = 0; j < size.X; j++)
                {//x
                    if (inventory.GetSlotCount(startIndex + j + i * size.X) > 0)
                    {
                        point.X = MathUtils.Min(point.X, j);
                        point.Y = MathUtils.Min(point.Y, i);
                    }
                }
            }
            int pos = 0;
            for (int i = point.Y; i < point.Y + size.Y; i++)
            {
                for (int j = point.X; j < point.X + size.X; j++)
                {
                    int p = j + i * size.X;
                    if (p < max)
                    {
                        result[pos++] = inventory.GetSlotValue(startIndex + j + i * size.X);
                    }
                    else
                    {
                        result[pos++] = 0;
                    }
                }
            }
        }
    }
}
